package com.liuceng.zen.service;

import com.liuceng.zen.mapper.AdDirectedGroupRelMapper;
import com.liuceng.zen.mapper.FrontAdGroupMapper;
import com.liuceng.zen.mapper.FrontGroupCreativeRelMapper;
import com.liuceng.zen.pojo.domain.*;
import com.liuceng.zen.pojo.form.FrontAdGroupForm;
import com.liuceng.zen.web.auth.utils.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.remoting.support.RemoteInvocation;
import org.springframework.remoting.support.RemoteInvocationResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.sun.tools.javac.jvm.ByteCodes.ret;

@Service
public class FrontAdGroupService extends BaseService<FrontAdGroup> {

  private Logger logger = LoggerFactory.getLogger(getClass());

  private final static Short OWNED_OPERATION = 2;
  @Autowired
  MemberDepartmentRelKeyService memberDepartmentRelKeyService;
  @Autowired
  private FrontAdGroupMapper frontAdGroupMapper;
  @Autowired
  private DepartmentService departmentService;
  @Autowired
  private AdminService adminService;
  @Autowired
  private MemberOperationNotificationService memberOperationNotificationService;
  @Autowired
  private SmsSenderService smsSenderService;
  @Autowired
  MessageService messageService;
  @Autowired
  private FrontCampaignService frontCampaignService;
  @Autowired
  private AmqpTemplate amqpTemplate;
  @Autowired
  private AdDirectedGroupRelMapper adDirectedGroupRelMapper;
  @Autowired
  private FrontGroupCreativeRelService frontGroupCreativeRelService;
  @Autowired
  private OperatingTrackService operatingTrackService;
  @Autowired
  private FrontGroupCreativeRelMapper frontGroupCreativeRelMapper;
  @Autowired
  private MemberService memberService;

  public String getMobileOfferMessage() {
    return "建议出价" + RandomUtils.random(2.8, 3.1) + "~" + RandomUtils.random(3.3, 3.7);
  }

  public String getPcOfferMessage() {
    return "建议出价" + RandomUtils.random(4.9, 5.2) + "~" + RandomUtils.random(5.5, 5.8);
  }

  /**
   * 从队列中按照广告id获取广告出价，如果获取不到则直接取数据库中的广告出价
   * @param adGroupId
   * @param frontAdGroup
   * @return
   */
  public BigDecimal getAdOffer(Integer adGroupId,FrontAdGroup frontAdGroup){
    RemoteInvocationResult result = (RemoteInvocationResult) amqpTemplate
            .convertSendAndReceive("hlt.ad_offer.queue",new RemoteInvocation("getAdOffer"
                    ,new Class[]{String.class},new Object[]{""+adGroupId}));
    if(StringUtils.isNotBlank(result.getValue().toString())&&null!=result.getValue()){
      return new BigDecimal(result.getValue().toString());
    }else{
      return frontAdGroup.getAdOffer();
    }
  }

  /**
   *从队列中按照广告类型和客户id获取广告最低出价，如果获取不到则直接取数据库中的广告最低出价
   * @param frontCampaignType
   * @param member
   * @return
   */
  public BigDecimal getMinAdOffer(Integer frontCampaignType,Member member){
    RemoteInvocationResult result = (RemoteInvocationResult) amqpTemplate
            .convertSendAndReceive("hlt.ad_min_offer.queue",new RemoteInvocation("getAdMinOffer"
                    ,new Class[]{String.class,String.class},new Object[]{""+member.getId(),""+frontCampaignType}));
    if(StringUtils.isNotBlank(result.getValue().toString())&&null!=result.getValue()){
      return new BigDecimal(result.getValue().toString());
    }else{
      if(1==frontCampaignType){
        return member.getPcMinAdOffer();
      }else{
        return member.getMobileMinAdOffer();
      }
    }
  }
  @Transactional
  public FrontAdGroup save(FrontAdGroup frontAdGroup) {
    frontAdGroup.setCreatedAt(new Date());
    frontAdGroup.setUpdatedAt(new Date());
    frontAdGroupMapper.insertSelective(frontAdGroup);
    return frontAdGroup;
  }

  /**
   * 操作正在投放的广告变成暂停状态或者由暂停变成开始投放
   * 
   * @param frontAdGroupId
   */
  @Transactional
  public void changeAdGroupType(Integer frontAdGroupId,Integer memberId,Member member) {
    FrontAdGroup frontAdGroup = super.find(frontAdGroupId);
    //计划下当在投广告数量小于1时，生成操作动态
    Map<String,Object> map = new HashMap<>();
    map.put("memberId",memberId);
    map.put("time",new Date());
    map.put("frontCampaignType",frontAdGroup.getFrontCampaignType());
    List<FrontAdGroup> adGroups = frontAdGroupMapper.findAdGroups(map);

    // 正在投放的广告变成暂停状态
    if (frontAdGroup.getFrontAdGroupType() == FrontAdGroup.IS_BEING_PUT) {
      if(adGroups.size()==1){
        String operateObject=frontAdGroup.getFrontCampaignType().intValue()==1?"pc计划所有广告":"移动计划所有广告";
        operatingTrackService.addOperatingTrack(member,operateObject,"暂停广告",frontAdGroup.getId(),null, null,null);
      }
      frontAdGroup.setFrontAdGroupType(FrontAdGroup.STOP);
    }
    // 由暂停变成开始投放
    else if (frontAdGroup.getFrontAdGroupType() == FrontAdGroup.STOP) {
      if(adGroups.size()==0||adGroups==null){
        operatingTrackService.addOperatingTrack(member,frontAdGroup.getTitle(),"开启广告",frontAdGroup.getId(),null, null,null);
      }
      frontAdGroup.setFrontAdGroupType(FrontAdGroup.IS_BEING_PUT);
    }
    super.update(frontAdGroup);
    //processAdGroupPutLife(frontAdGroup);
  }

  /**
   * 获取当前广告状态
   * 
   * @param adId
   * @return
   */
  public boolean isAdIsBeingPut(Integer adId) {
    FrontAdGroup frontAdGroup = find(adId);
    if (frontAdGroup == null) {
      return false;
    }
    //
    Integer frontAdGroupType = frontAdGroup.getFrontAdGroupType();

    Integer campaignId = frontAdGroup.getFrontCampaignId();
    FrontCampaign frontCampaign = frontCampaignService.find(campaignId);
    Integer adPutType = frontAdGroup.getAdPutType();
    Date startTime = frontAdGroup.getAdPutStartAt();
    Date endTime = frontAdGroup.getAdPutEndAt();
    // 广告计划关闭
    if (frontCampaign.getCampaignStatus() != FrontCampaign.START_STATUS) {
      return false;
    }
    if (frontAdGroupType == FrontAdGroup.IS_BEING_PUT && adPutType != FrontAdGroup.BEEN_PUT_ON) {
      // 还没到投放时间段
      if (startTime.after(new Date())) {
        return false;
      }
      // 超时
      if (endTime.before(new Date())) {
        return false;
      }
    }
    // 正在投放中
    if (frontAdGroupType == FrontAdGroup.IS_BEING_PUT) {
      return true;
    }
    return false;
  }

  public Integer selectAdGroupCount(Integer memberId) {
    Map<String, Object> map = new HashMap<>();
    map.put("memberId", memberId);
    List<FrontAdGroup> frontAdGroups = super.search(map);
    if (frontAdGroups != null && frontAdGroups.size() > 0) {
      return frontAdGroups.size();
    } else {
      return 0;
    }
  }
  @Transactional
  public void processAdGroupPutLife(FrontAdGroup adgroup) {

    if (isAdIsBeingPut(adgroup.getId())) {
      amqpTemplate.convertAndSend(BaseService.DIRECT_EXCHANGE, "hlt.ad_life_quene",
          adgroup.getMemberId() + ":" + adgroup.getFrontCampaignId() + ":" + adgroup.getId() + ":set-zen");
    } else {
      // 清空redis里面广告生存时间
      amqpTemplate.convertAndSend(BaseService.DIRECT_EXCHANGE, "hlt.ad_life_quene",
          adgroup.getMemberId() + ":" + adgroup.getFrontCampaignId() + ":" + adgroup.getId() + ":clear-zen");
    }
  }

  /**
   * 新建广告
   * @param form
   * @param memberId
   * @param member
   */
  @Transactional
  public void addFrontAdGroup(FrontAdGroupForm form, Integer memberId, Member member){
    Member currentMember=memberService.find(member.getId());
    //1 新建广告
    FrontAdGroup frontAdGroup = new FrontAdGroup();
    //账户余额大于0的时候,后台显示待审核
    if((null==currentMember.getBalance()?new BigDecimal("0"):currentMember.getBalance()).compareTo(BigDecimal.ZERO)==1){
      frontAdGroup.setFrontAdGroupType(form.IS_BEING_REVIEWED);
    }else{
      //账户余额不大于0的时候,后台不审核
      frontAdGroup.setFrontAdGroupType(form.FRONT_IS_BEING_REVIEWED);
    }
    frontAdGroup.setAdPutType(form.getAdPutType());
    if (form.getAdPutType() == 2) {
      try {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        frontAdGroup.setAdPutStartAt(simple.parse(form.getAdPutStartAt() + " 00:00:00"));
        frontAdGroup.setAdPutEndAt(simple.parse(form.getAdPutEndAt() + " 23:59:59"));
      } catch (ParseException e) {
        logger.error(e.getMessage() + e);
      }
    }
    frontAdGroup.setCreatedId(memberId);
    frontAdGroup.setMemberId(memberId);
    frontAdGroup.setTitle(form.getTitle());
    frontAdGroup.setDeleteFlag(FrontAdGroupForm.CREATIVE);
    frontAdGroup.setPromotionGoal(form.getPromotionGoal());
    //添加广告出价
    frontAdGroup.setAdOffer(form.getAdOffer());

    //2 获取计划数据
    Map<String, Object> map = new HashMap<>();
    map.put("memberId", memberId);
    map.put("campaignType", form.getFrontCampaignType());
    FrontCampaign frontCampaign = frontCampaignService.findOneByParams(map);
    frontAdGroup.setFrontCampaignId(frontCampaign.getId());
    frontAdGroup.setFrontCampaignName(frontCampaign.getName());
    frontAdGroup.setFrontCampaignType(frontCampaign.getCampaignType());// 1pc 2移动

    frontAdGroup.setDiyFormId(form.getDiyFormId());
    frontAdGroup.setUpdatedId(memberId);
    frontAdGroup.setCreatedId(memberId);
    FrontAdGroup news = save(frontAdGroup);
    //账户余额大于0的时候后台生成操作操作动态
    if((null==currentMember.getBalance()?new BigDecimal("0"):currentMember.getBalance()).compareTo(BigDecimal.ZERO)==1){
      //3 添加新建广告操作轨迹
      operatingTrackService.addOperatingTrack(member, form.getTitle(), "新建广告", news.getId(), null, null, null);
    }
    //4 添加定向
    List<Integer> adTargetId = form.getAdTargetId();
    List<AdDirectedGroupRel> Ads = new ArrayList<>();
    if (adTargetId.size() > 0) {
      for (Integer ids:adTargetId) {
        AdDirectedGroupRel adDirectedGroupRel = new AdDirectedGroupRel();
        adDirectedGroupRel.setAdGroupId(news.getId());
        adDirectedGroupRel.setAdDirectedId(ids);
        Ads.add(adDirectedGroupRel);
      }
      adDirectedGroupRelMapper.batchInsert(Ads);
    }
    //5 添加创意
    List<FrontGroupCreativeRel> frontCreatives = new ArrayList<>();
    List<Integer> creativeIds = form.getCreativesId();
    if (creativeIds != null && creativeIds.size() != 0) {
      for (Integer id:creativeIds) {
        FrontGroupCreativeRel frontGroupCreativeRel = new FrontGroupCreativeRel();
        frontGroupCreativeRel.setFrontAdGroupId(news.getId());
        frontGroupCreativeRel.setFrontSelfOperateCreativeId(id);
        frontCreatives.add(frontGroupCreativeRel);

      }
      frontGroupCreativeRelService.batchInsert(frontCreatives);
    }
  }

  /**
   * 删除广告
   * @param frontAdGroupId
   * @param hailiangtong
   * @param member
   */
  @Transactional
  public void deleteFrontAdGroup(Integer frontAdGroupId,String hailiangtong,Member member){
    //1 更新广告为删除状态
    FrontAdGroup f = super.find(frontAdGroupId);
    f.setDeleteFlag(FrontAdGroupForm.DELETE);
    f.setDeletedAt(new Date());
    Short operationType = member.getOperationType();
    // 2判断自运营
    if (OWNED_OPERATION.shortValue() == operationType.shortValue()) {
      //假的审核状态不添加轨迹
      if(f.getFrontAdGroupType().intValue()!=FrontAdGroupForm.FRONT_IS_BEING_REVIEWED.intValue()){
        //3 添加删除广告操作轨迹
        operatingTrackService.addOperatingTrack(member, f.getTitle(), "删除广告",
                f.getId(), null, null, null);
      }
      //4 删除广告创意,广告定向中间表
      Map<String, Object> adGroupId = new HashMap<>();
      adGroupId.put("frontAdGroupId", frontAdGroupId);
      adDirectedGroupRelMapper.deleteByAdGroupId(adGroupId);
      frontGroupCreativeRelMapper.deleteByAdGroupId(adGroupId);

      //5 获取管理该客户的运营人员
      Map<String, Object> maps = new HashMap<>();
      maps.put("memberId", member.getId());
      maps.put("mediumType", f.getFrontCampaignType());

      List<MemberDepartmentRelKey> memberDepartmentRelKeys =
              memberDepartmentRelKeyService.findByParams(maps);
      SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      //6 没有运营人员，则发送给创建该客户的分公司管理员
      if (memberDepartmentRelKeys != null && memberDepartmentRelKeys.size() > 0) {
        for (int i = 0; i < memberDepartmentRelKeys.size(); i++) {
          Integer adminId = memberDepartmentRelKeys.get(i).getAdminId();
          Timer timer = new Timer();
          TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
              MemberOperationNotification memberOperationNotification =
                      new MemberOperationNotification();
              memberOperationNotification.setMemberId(member.getId());
              memberOperationNotification.setCompanyName(member.getCompanyName());
              memberOperationNotification.setDataFlag(MemberOperationNotification.UNTREATED);
              memberOperationNotification.setAction(MemberOperationNotification.DELETE_AD_GROUP);
              memberOperationNotification.setCampaignId(f.getFrontCampaignId());
              memberOperationNotification.setAdGroupId(frontAdGroupId);
              memberOperationNotification.setAdminId(adminId);
              Admin admin = adminService.find(adminId);
              memberOperationNotification.setAdminName(admin.getName());
              memberOperationNotification.setDepartmentId(admin.getDepartmentId());
              Department department = departmentService.find(admin.getDepartmentId());
              memberOperationNotification.setDepartmentName(department.getName());
              memberOperationNotificationService.insert(memberOperationNotification);
              // 新版短信平台
              String content =
                      "客户" + member.getCompanyName() + "于" + simple.format(f.getUpdatedAt()) + "对广告："
                              + f.getTitle() + "进行了" + memberOperationNotification.getAction()
                              + "操作，请及时处理。收到信息请点击下面的链接进行确认：" + hailiangtong
                              + "/member_operation_notification/edit/" + memberOperationNotification.getId()
                              + "【海量通】";
              Date date = smsSenderService.sender(admin.getPhone(), content);
              logger.info(content);// 打印短信日志
              memberOperationNotification.setContent(content);
              memberOperationNotificationService.update(memberOperationNotification);
              messageService.timerTaskAdGroup(memberOperationNotification, admin, member, f, new Date());
              if(date!=null){
                cancel();
              }
            }
          };
          timer.schedule(timerTask, 5*i);
        }
      } else {
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
          @Override
          public void run() {
            MemberOperationNotification memberOperationNotification = new MemberOperationNotification();
            memberOperationNotification.setMemberId(member.getId());
            memberOperationNotification.setCompanyName(member.getCompanyName());
            memberOperationNotification.setDataFlag(MemberOperationNotification.UNTREATED);
            memberOperationNotification.setAction(MemberOperationNotification.DELETE_AD_GROUP);
            memberOperationNotification.setCampaignId(f.getFrontCampaignId());
            memberOperationNotification.setAdGroupId(frontAdGroupId);
            memberOperationNotification.setAdminId(member.getAdminId());
            Admin admin = adminService.find(member.getAdminId());
            memberOperationNotification.setAdminName(admin.getName());
            memberOperationNotification.setDepartmentId(admin.getDepartmentId());
            Department department = departmentService.find(admin.getDepartmentId());
            memberOperationNotification.setDepartmentName(department.getName());
            memberOperationNotificationService.insert(memberOperationNotification);
            // 新版短信平台
            String content =
                    "客户" + member.getCompanyName() + "于" + simple.format(f.getUpdatedAt()) + "对广告："
                            + f.getTitle() + "进行了" + memberOperationNotification.getAction()
                            + "操作，请及时处理。收到信息请点击下面的链接进行确认：" + hailiangtong
                            + "/member_operation_notification/edit/" + memberOperationNotification.getId()
                            + "【海量通】";
            Date date = smsSenderService.sender(admin.getPhone(), content);
            logger.info(content);// 打印短信日志
            memberOperationNotification.setContent(content);
            memberOperationNotificationService.update(memberOperationNotification);
            messageService.timerTaskAdGroup(memberOperationNotification, admin, member, f, new Date());
            if(date!=null){
              cancel();
            }
          }
        };
        timer.schedule(timerTask, 0);
      }
    }
    super.update(f);
  }

  @Transactional
  public void editFrontAdGroup(FrontAdGroupForm form,Integer frontAdGroupId,Member member,String hailiangtong){
    //1 设置时间格式
    SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    //2 获取客户详情和创建该客户的公司管理员资料
    Admin admin = adminService.find(member.getAdminId());
    // 自营修改广告有短信提醒
    //3 获取客户类型
    Short operationType = member.getOperationType();
    //4 获取广告
    FrontAdGroup frontAdGroup = super.find(frontAdGroupId);
    //为修改之前的广告状态
    Integer boforeEditType=frontAdGroup.getFrontAdGroupType();

    //5 判断：如果该广告为审核不通过状态,则直接变为待审核状态
    if(form.AUDIT_NOT_THROUGH.intValue()==frontAdGroup.getFrontAdGroupType().intValue()){
      frontAdGroup.setFrontAdGroupType(form.IS_BEING_REVIEWED);
      //不是，假审核状态，添加轨迹
      if(boforeEditType.intValue()!=FrontAdGroupForm.FRONT_IS_BEING_REVIEWED.intValue()){
        // 添加广告由不通过状态变为待审核状态操作轨迹
        operatingTrackService.addOperatingTrack(member, form.getTitle(), "二次提交", frontAdGroup.getId(), null, null, null);
      }
    }

    //6 判断：编辑广告时,修改广告投放时间要添加轨迹,并向后台发送提醒,不需要重新审核
    if (form.getAdPutType().intValue() != frontAdGroup.getAdPutType().intValue()) {
      //广告投放方式类型改变才存
      frontAdGroup.setAdPutType(form.getAdPutType());
      //7 将修改后的广告投放时间存入数据库
      if (form.getAdPutType().intValue() == 2) {
        try {
          frontAdGroup.setAdPutStartAt(simple.parse(form.getAdPutStartAt() + " 00:00:00"));
          frontAdGroup.setAdPutEndAt(simple.parse(form.getAdPutEndAt() + " 23:59:59"));
        } catch (ParseException e) {
          logger.error(e.getMessage() + e);
        }
      }
      if(boforeEditType.intValue()!=FrontAdGroupForm.FRONT_IS_BEING_REVIEWED.intValue()){
        // 添加修改广告投放时间操作轨迹
        operatingTrackService.addOperatingTrack(member, form.getTitle(), "修改投放时间", frontAdGroup.getId(), null, null, null);
      }
    } else {
      String adPutStartAt =
              null == frontAdGroup.getAdPutStartAt() ? "" : format.format(frontAdGroup.getAdPutStartAt());
      String adPutEndAt =
              null == frontAdGroup.getAdPutEndAt() ? "" : format.format(frontAdGroup.getAdPutEndAt());
      if (!adPutStartAt.equals(form.getAdPutStartAt()) || !adPutEndAt.equals(form.getAdPutEndAt())) {
        //7 将修改后的广告投放时间存入数据库
        if (form.getAdPutType() == 2) {
          try {
            frontAdGroup.setAdPutStartAt(simple.parse(form.getAdPutStartAt() + " 00:00:00"));
            frontAdGroup.setAdPutEndAt(simple.parse(form.getAdPutEndAt() + " 23:59:59"));
          } catch (ParseException e) {
            logger.error(e.getMessage() + e);
          }
        }
        if(boforeEditType.intValue()!=FrontAdGroupForm.FRONT_IS_BEING_REVIEWED.intValue()){
          // 添加修改广告投放时间操作轨迹
          operatingTrackService.addOperatingTrack(member, form.getTitle(), "修改投放时间", frontAdGroup.getId(), null, null, null);
        }
      }
    }
    frontAdGroup.setTitle(form.getTitle());
    frontAdGroup.setUpdatedAt(new Date());
    frontAdGroup.setUpdatedId(member.getId());
    frontAdGroup.setPromotionGoal(form.getPromotionGoal());
    //添加广告出价
    frontAdGroup.setAdOffer(form.getAdOffer());
    //8 获取计划数据
    Map<String, Object> map = new HashMap<>();
    map.put("memberId", member.getId());
    map.put("campaignType", form.getFrontCampaignType());
    FrontCampaign frontCampaign = frontCampaignService.findOneByParams(map);

    frontAdGroup.setFrontCampaignId(frontCampaign.getId());
    frontAdGroup.setFrontCampaignName(frontCampaign.getName());
    frontAdGroup.setFrontCampaignType(frontCampaign.getCampaignType());// 1pc 2移动

    //9 编辑广告时,更改广告落地页要添加轨迹,并向后台发送提醒,需要重新审核
    if (frontAdGroup.getDiyFormId().intValue()!=form.getDiyFormId().intValue()) {
      if(boforeEditType.intValue()!=FrontAdGroupForm.FRONT_IS_BEING_REVIEWED.intValue()){
        operatingTrackService.addOperatingTrack(member, frontAdGroup.getTitle(), "更换落地页", frontAdGroup.getId(), null, null, null);
      }
      frontAdGroup.setFrontAdGroupType(FrontAdGroupForm.IS_BEING_REVIEWED);
      frontAdGroup.setDiyFormId(form.getDiyFormId());
    }

    Map<String, Object> adGroupId = new HashMap<>();
    adGroupId.put("frontAdGroupId", frontAdGroupId);
    //10 旧的定向
    List<Integer> adDirectId = adDirectedGroupRelMapper.selectSelfCreativeId(adGroupId);
    Collections.sort(adDirectId);
    //11 旧的创意
    List<Integer> creativeId = frontGroupCreativeRelMapper.selectSelfCreativeId(adGroupId);
    Collections.sort(creativeId);
    //12 新的定向和创意
    List<Integer> adTargetIds = form.getAdTargetId();
    List<Integer> creativeIds = form.getCreativesId();
    Collections.sort(adTargetIds);
    Collections.sort(creativeIds);
    String oldAdDirectId = StringUtils.join(adDirectId, ",");
    String newAdDirectId = StringUtils.join(adTargetIds, ",");
    String oldCreativeId = StringUtils.join(creativeId, ",");
    String newCreativeId = StringUtils.join(creativeIds, ",");
    //13 比较定向和创意
    if (!oldAdDirectId.equals(newAdDirectId)) {
      //14 删除旧的定向中间表
      adDirectedGroupRelMapper.deleteByAdGroupId(adGroupId);
      //15 添加新的定向
      List<AdDirectedGroupRel> Ads = new ArrayList<>();
      if (adTargetIds.size() > 0) {
        for (Integer ids:adTargetIds) {
          AdDirectedGroupRel adDirectedGroupRel = new AdDirectedGroupRel();
          adDirectedGroupRel.setAdGroupId(frontAdGroupId);
          adDirectedGroupRel.setAdDirectedId(ids);
          Ads.add(adDirectedGroupRel);
        }
        adDirectedGroupRelMapper.batchInsert(Ads);
      }
      if(boforeEditType.intValue()!=FrontAdGroupForm.FRONT_IS_BEING_REVIEWED.intValue()){
        // 编辑广告时,修改广告投放定向人群要添加轨迹,并向后台发送提醒,不需要重新审核
        operatingTrackService.addOperatingTrack(member, frontAdGroup.getTitle(), "修改定向", frontAdGroup.getId(), null, null, null);
      }
    }
    if (!oldCreativeId.equals(newCreativeId)) {
      //14 删除旧的广告创意中间表
      frontGroupCreativeRelMapper.deleteByAdGroupId(adGroupId);
      //16 添加新的创意
      List<FrontGroupCreativeRel> frontCreatives = new ArrayList<>();
      if (creativeIds != null && creativeIds.size() != 0) {
        for (Integer ids:creativeIds) {
          // 获取物料
          FrontGroupCreativeRel frontGroupCreativeRel = new FrontGroupCreativeRel();
          frontGroupCreativeRel.setFrontAdGroupId(frontAdGroupId);
          frontGroupCreativeRel.setFrontSelfOperateCreativeId(ids);
          frontCreatives.add(frontGroupCreativeRel);
        }
        frontGroupCreativeRelService.batchInsert(frontCreatives);
      }
      if(boforeEditType.intValue()!=FrontAdGroupForm.FRONT_IS_BEING_REVIEWED.intValue()){
        // 编辑广告时,更改广告创意要添加轨迹,并向后台发送提醒,需要重新审核
        operatingTrackService.addOperatingTrack(member, frontAdGroup.getTitle(), "更换创意", frontAdGroup.getId(), null, null, null);
      }
      frontAdGroup.setFrontAdGroupType(FrontAdGroupForm.IS_BEING_REVIEWED);
    }
    //如果原来为假审核状态的话，还是假审核状态
    if(boforeEditType.intValue()==FrontAdGroupForm.FRONT_IS_BEING_REVIEWED.intValue()){
      frontAdGroup.setFrontAdGroupType(FrontAdGroupForm.FRONT_IS_BEING_REVIEWED);
    }
    super.update(frontAdGroup);
    //17 自营修改广告有短信提醒，代运营修改广告不需要短信提醒
    if (OWNED_OPERATION == operationType) {

      long starTime=System.currentTimeMillis();
      Timer timer = new Timer();
      TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
          MemberOperationNotification memberOperationNotification = new MemberOperationNotification();
          memberOperationNotification.setMemberId(member.getId());
          memberOperationNotification.setCompanyName(member.getCompanyName());
          memberOperationNotification.setDataFlag(MemberOperationNotification.UNTREATED);
          memberOperationNotification.setAction(MemberOperationNotification.EDIT_AD_GROUP);
          memberOperationNotification.setCampaignId(frontAdGroup.getFrontCampaignId());
          memberOperationNotification.setAdGroupId(frontAdGroupId);
          memberOperationNotification.setAdminId(member.getAdminId());
          memberOperationNotification.setAdminName(admin.getName());
          memberOperationNotification.setDepartmentId(admin.getDepartmentId());
          Department department = departmentService.find(admin.getDepartmentId());
          memberOperationNotification.setDepartmentName(department.getName());
          memberOperationNotificationService.insert(memberOperationNotification);
          String content =
                  "客户" + member.getCompanyName() + "于" + simple.format(frontAdGroup.getUpdatedAt())
                          + "对广告：" + frontAdGroup.getTitle() + "进行了" + memberOperationNotification.getAction()
                          + "操作，请及时处理。收到信息请点击下面的链接进行确认：" + hailiangtong
                          + "/member_operation_notification/edit/" + memberOperationNotification.getId()
                          + "【海量通】";
          Date date = smsSenderService.sender(admin.getPhone(), content);
          logger.info(content);// 打印短信日志
          memberOperationNotification.setContent(content);
          memberOperationNotificationService.update(memberOperationNotification);
          messageService.timerTaskAdGroup(memberOperationNotification, admin, member, frontAdGroup, new Date());
          if(date!=null){
            cancel();
          }
        }
      };
      timer.schedule(timerTask, 0);
      long endTime=System.currentTimeMillis();
      logger.info("广告修改发送短信时间为："+(endTime-starTime));
    }
  }
}
